package services;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;

import models.Report;
import services.jaxb.report.Robot;
import services.jaxb.report.Status;
import services.jaxb.report.Suite;

public class ReportService {
	
	private static final String PATH_SEPARATOR = "/";
	private static final String REPORT_OUTPUT_XML = "output.xml";
	private static final String REPORT_OUTPUT_HTML = "report.html";
	
	private static ReportService service;
	
	private SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd HH:mm:ss.SSS");
	
	// Singleton pattern
	private ReportService() {
		
	}
	
	public static ReportService getService() {
		if (service == null)
			service = new ReportService();
		return service;
	}
	
	public Report createReportModel(String projectName, String reportDirectoryName, String reportRepositoryPath) {
		Robot robotReport = getRobotReport(projectName, reportDirectoryName, reportRepositoryPath);
		if (robotReport == null) {
			return null;
		}
		Report report = new Report();
		report.setId(Long.parseLong(reportDirectoryName));
		report.setProject(projectName);
		report.setStatus(getStatus(robotReport.getSuite()));
		report.setPath(getReportHtmlPath(projectName, reportDirectoryName, reportRepositoryPath));
		try {
			report.setGeneratedTime(sdf.parse(robotReport.getGenerated()));
		} catch (ParseException ex) {
			ex.printStackTrace();
		}
		return report;
	}
	
	private String getStatus(Suite suite) {
		if (suite == null)
			return null;
		List<Object> elements = suite.getKwOrSuiteOrTest();
		int i = 0;
		while (true) {
			if (i >= elements.size())
				break;
			Object obj = elements.get(i++);
			if (obj instanceof Status) {
				Status status = (Status) obj;
				return status.getStatus();
			}
			
		}
		return null;
	}
	
	private String getReportOutputPath(String projectName, String reportDirectoryName, String reportRepositoryPath) {
		return reportRepositoryPath + PATH_SEPARATOR + projectName + PATH_SEPARATOR + reportDirectoryName + PATH_SEPARATOR + REPORT_OUTPUT_XML;
	}
	
	public String getReportHtmlPath(String projectName, String reportDirectoryName, String reportRepositoryPath) {
		return reportRepositoryPath + PATH_SEPARATOR + projectName + PATH_SEPARATOR + reportDirectoryName + PATH_SEPARATOR + REPORT_OUTPUT_HTML;
	}
	
	private Robot getRobotReport(String projectName, String reportDirectoryName, String reportRepositoryPath) {
		try {
			JAXBContext jc = JAXBContext.newInstance("services.jaxb.report", Robot.class.getClassLoader());
			javax.xml.bind.Unmarshaller unmarshaller = jc.createUnmarshaller();
			return (Robot) unmarshaller.unmarshal(new File(getReportOutputPath(projectName, reportDirectoryName, reportRepositoryPath)));
			
		} catch (JAXBException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
}
